import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }

    public void createHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }

        // 时间复杂度:O(N)
        for (int p = (usedSize-1-1)/2; p >= 0; p--) {
            shiftDown(p, usedSize);
        }
    }

    // 时间复杂度:O(logN)

    /**
     * 向下调整：大根堆
     * @param root
     * @param len
     */
    public void shiftDown(int root, int len) {
        int parent = root;
        int child = 2*parent+1;

        while (child < len) {
            if (child+1 < len && elem[child] < elem[child+1]) {
                child++;
            }

            if (elem[parent] < elem[child]) {
                int tmp = elem[parent];
                elem[parent] = elem[child];
                elem[child] = tmp;
                parent = child;
                child = 2*parent+1;
            }else{
                break;
            }
        }
    }

    public void push(int val) {
        if (isFull()) {
            elem = Arrays.copyOf(elem, 2*elem.length);
        }
        elem[usedSize] = val;

        shiftUp(usedSize);
        usedSize++;
    }

    /**
     * 向上调整
     * @param child
     */
    private void shiftUp(int child) {
        int parent = (child-1)/2;
        while (parent >= 0) {
            if (elem[child] > elem[parent]) {
                int tmp = elem[parent];
                elem[parent] = elem[child];
                elem[child] = tmp;

                child = parent;
                parent = (child-1)/2;
            }else {
                break;
            }
        }
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    public void pollHeap() {
        if (isEmpty()) {
            System.out.println("优先级队列为空！");
            return;
        }

        int tmp = elem[0];
        elem[0] = elem[usedSize-1];
        elem[usedSize-1] = tmp;

        usedSize--;
        shiftDown(0, usedSize);
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    /**
     * 获取堆顶元素
     * @return
     */
    public int peekHeap() {
        if (isEmpty()) {
            System.out.println("优先级队列为空！");
            return -1;
        }

        return elem[0];
    }

    public void heapSort() {
        int end = usedSize - 1;
        while (end > 0) {
            int tmp = elem[0];
            elem[0] = elem[end];
            elem[end] = tmp;
            shiftDown(0, end);
            end--;
        }
    }
}
